import 'package:flutter/foundation.dart';

import 'plugin_secure_store_platform_interface.dart';

/// Author: bzb
/// Date: 2023/9/27 13:18
/// Desc: 本地安全密钥管理
/// Android使用 KeyStore
/// iOS使用 KeyChain
class PluginSecureStore {
  final MAX_DECRYPT_BLOCK = 11;

  static final _instance = PluginSecureStore._();
  PluginSecureStore._();

  static PluginSecureStore getInstance() => _instance;

  /// 生成一对RSA密钥, 返回公钥 Base64 字符串
  Future<String?> generateRSA(String alias) async {
    String? pubKey;
    try {
      pubKey = await PluginSecureStorePlatform.instance.generateRSA(alias);
      if (kDebugMode) print("密钥生成: pubKey=$pubKey<<<<");
    } catch (e) {
      print("PluginSecureStore generateRSA: $e");
    }
    return pubKey?.trim();
  }

  /// 使用RSA公钥进行加密, 返回加密后的 Base64 字符串
  Future<String?> encryptRSA(String alias, String content) async {
    String? encryptResult;
    try {
      encryptResult = await PluginSecureStorePlatform.instance.encryptRSA(alias, content);
      if (kDebugMode) print("加密: encryptResult=$encryptResult");
    } catch (e) {
      print("PluginSecureStore encryptRSA: $e");
    }
    return encryptResult;
  }

  /// 使用RSA私钥进行解密, 返回解密后的字符串
  /// @params content 入参需要 Base64 编码过的字符串
  Future<String?> decryptRSA(String alias, String content) async {
    String? decryptResult;
    try {
      if (kDebugMode) print("待解密: content=$content");
      decryptResult = await PluginSecureStorePlatform.instance.decryptRSA(alias, content);
      if (kDebugMode) print("解密: decryptResult=$decryptResult");
    } catch (e) {
      print("PluginSecureStore decryptRSA: $e");
    }
    return decryptResult;
  }

  /// 使用RSA私钥进行白盒密钥大数据解密, 返回解密后的字符串
  /// @params content 入参需要 Base64 编码过的字符串
  Future<String?> decryptBigRSA(String alias, String content) async {
    String? decryptResult;
    try {
      if (kDebugMode) print("待解密: content=$content");
      decryptResult = await PluginSecureStorePlatform.instance.decryptBigRSA(alias, content);
      if (kDebugMode) print("解密结果: decryptResult=$decryptResult");
    } catch (e) {
      print("PluginSecureStore decryptBigRSA: $e");
    }
    return decryptResult;
  }


}
